package com.techsoul.module.basic.controller;

import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.pojo.Result;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.log.annotation.Log;
import com.techsoul.common.log.enums.OperationTypeEnum;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.CustomerMapper;
import com.techsoul.module.basic.pojo.entity.Customer;
import com.techsoul.module.basic.pojo.param.CustomerSaveParam;
import com.techsoul.module.basic.pojo.param.CustomerSearchParam;
import com.techsoul.module.basic.pojo.param.StoreSearchParam;
import com.techsoul.module.basic.service.ICustomerService;
import com.techsoul.module.pms.pojo.entity.TWhWarehouseCustomerMaterial;
import com.techsoul.module.pms.pojo.vo.TWhWarehouseCustomerMaterialVo;
import com.techsoul.module.system.pojo.param.UserSaveParam;
import com.techsoul.module.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * 客户 Controller
 *
 * @author liuen
 * @date 2021-01-26
 */
@Api(tags = "客户")
@Slf4j
@RestController
@RequestMapping("/basic/customer")
public class CustomerController {

    @Autowired
    private Result result;
    @Autowired
    private ICustomerService service;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private TokenService tokenService;
    @ApiOperation("新增")
    @Log(title = "客户", operationType = OperationTypeEnum.INSERT)
    @PreAuthorize("hasAnyAuthority('basic:customer:insert')")
    @PostMapping
    public Result insert(@Valid @RequestBody CustomerSaveParam params) {
        return result.success(this.service.insert(params));
    }

    @ApiOperation("批量删除（多个用逗号隔开）")
    @Log(title = "客户", operationType = OperationTypeEnum.DELETE)
    @PreAuthorize("hasAnyAuthority('basic:customer:delete')")
    @DeleteMapping("/{ids}")
    public Result batchDelete(@PathVariable String[] ids) {
        return result.success(this.service.batchDelete(Arrays.asList(ids)));
    }

    @ApiOperation("批量删除（多个用逗号隔开）")
    @PreAuthorize("hasAnyAuthority('basic:customer:delete')")
    @PostMapping("/logicalDelete/{ids}")
    public Result logicalDelete(@PathVariable String[] ids) {
        return result.success(this.service.logicalDelete(Arrays.asList(ids)));
    }
    @ApiOperation("审核")
    @PreAuthorize("hasAnyAuthority('basic:customer:prove')")
    @PostMapping("/prove")
    public Result prove(@RequestBody CustomerSaveParam params) {

        String ret = service.prove(params);
        return result.success();

    }
    @ApiOperation("修改")
    @Log(title = "客户", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('basic:customer:update')")
    @PutMapping
    public Result update(@Valid @RequestBody CustomerSaveParam params) {
        return result.success(this.service.update(params));
    }
    @ApiOperation("修改")
    @PreAuthorize("hasAnyAuthority('system:user:updateCompany')")
    @PostMapping("/updateCompany")
    public Result updateCompany(@Valid @RequestBody CustomerSaveParam params) {
        return result.success(this.service.update(params));
    }

    @ApiOperation("修改")
    @PreAuthorize("hasAnyAuthority('system:user:updateCompany')")
    @PostMapping("/updateCompanyUser")
    public Result updateCompanyUser(@Valid @RequestBody UserSaveParam params) {
        if(params.getCustomerId()!=null&&params.getCustomerId()!=""){
            Customer customer = this.customerMapper.selectById(params.getCustomerId());
            customer.setAdminUserId(params.getId());
            UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
            customer.preUpdate(user.getId());
             this.customerMapper.updateById(customer);
        }
        return result.success(this.iUserService.update(params));
    }
    @ApiOperation("导入")
    @PreAuthorize("hasAnyAuthority('pms:tWhWarehouseCustomerMaterial:import')")
    @PostMapping("/importCustomerMaterialData")
    public Result importCustomerMaterialData(MultipartFile file) {
        List<TWhWarehouseCustomerMaterialVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();


        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(TWhWarehouseCustomerMaterialVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }

        if(dataList==null||dataList.size()==0){
            //return "没有读取到数据";
            log.error("没有读取到数据!");
        }

        int itemNo = 0;
        int line = 0;
        TWhWarehouseCustomerMaterial tWhWarehouseCustomerMaterial = new TWhWarehouseCustomerMaterial();
        for (TWhWarehouseCustomerMaterialVo data : dataList) {
            successNum++;
            line++;
            tWhWarehouseCustomerMaterial=this.service.importData(data,user,itemNo,line);

            itemNo = itemNo++;
        }

        return result.success(successMsg.toString());
    }

    @ApiOperation("修复数据")
    @PreAuthorize("hasAnyAuthority('basic:customer:update')")
    @PostMapping("/fixdata")
    public Result fixdata(@RequestBody CustomerSaveParam params) {
        this.service.fixdata();
        return result.success();
    }
    @ApiOperation("我的详情")
    @PreAuthorize("hasAnyAuthority('basic:customer:search')")
    @PostMapping("/getMyCustInfor")
    public Result getMyCustInfor(@RequestBody CustomerSearchParam params) {
        return result.success(this.service.getMyCustInfor());
    }

    @ApiOperation("详情")
    @PreAuthorize("hasAnyAuthority('basic:customer:search')")
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") String id) {
        return result.success(this.service.findById(id));
    }

    @ApiOperation("列表")

    @PostMapping("/search")
    public Result findAll(@RequestBody CustomerSearchParam params) {
        return result.success(this.service.findAll(params));
    }

    @ApiOperation("校验商城客户编码")
    @Log(title = "校验商城客户编码", operationType = OperationTypeEnum.UPDATE)
    @PreAuthorize("hasAnyAuthority('basic:customer:update')")
    @PostMapping("/checkCode")
    public Result checkCode(@Valid @RequestBody CustomerSearchParam params) {
        return result.success(this.service.checkCode(params));
    }
    @ApiOperation("列表-分页")
    @PreAuthorize("hasAnyAuthority('basic:customer:search')")
    @PostMapping("/search/{current}/{pageSize}")
    public Result findAll(@RequestBody CustomerSearchParam params, @PathVariable Integer current, @PathVariable Integer pageSize) {
        return result.success(this.service.findAll(params, current, pageSize));
    }
    @ApiOperation("新增银行")
    // @Log(title = "新增银行用户", operationType = OperationTypeEnum.INSERT)
    @PostMapping("/insertFactoryUser")
    public Result insertFactoryUser(@Valid @RequestBody UserSaveParam params) {
        params.setUserType("企业");
        return result.success(this.service.insertBizUser(params));
    }
    @ApiOperation("新增企业")
    // @Log(title = "新增企业用户", operationType = OperationTypeEnum.INSERT)
    @PostMapping("/insertBankUser")
    public Result insertBankUser(@Valid @RequestBody UserSaveParam params) {
        params.setUserType("银行");
        return result.success(this.service.insertBizUser(params));
    }

}
